package cn.knightzz.service.impl;

import cn.knightzz.entity.SysMenu;
import cn.knightzz.entity.SysRoleMenu;
import cn.knightzz.helper.MenuHelper;
import cn.knightzz.mapper.SysMenuMapper;
import cn.knightzz.mapper.SysRoleMenuMapper;
import cn.knightzz.service.SysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author knightzz
 * @since 2021-04-18
 */
@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    SysMenuMapper menuMapper;

    @Resource
    SysRoleMenuMapper roleMenuMapper;

    /**
     * 根据角色id获取菜单列表 - 树形结构
     *
     * @param roleId
     * @return
     */
    @Override
    public List<SysMenu> getTreeMenu(Integer roleId) {
        // 根据id 获取相应的菜单列表
        List<SysMenu> menuByRoleId = menuMapper.getMenuByRoleId(roleId);
        return MenuHelper.build(menuByRoleId);
    }

    @Override
    public List<SysMenu> getAllMenuByTree() {
        List<SysMenu> sysMenus = menuMapper.selectList(null);
        return MenuHelper.build(sysMenus);
    }

    /**
     * 添加菜单
     *
     * @param menu
     * @return
     */
    @Override
    public Boolean addMenus(SysMenu menu) {
        int insert = 0;
        try {
            insert = menuMapper.insert(menu);
        } catch (Exception e) {
            log.warn("addMenus Exception =>>>>>>>>>>>>>>>>>>>>>>>>>>");
            e.printStackTrace();
            return false;
        }
        return insert != 0 ;
    }

    /**
     * 更新菜单信息
     *
     * @param menu
     * @return
     */
    @Override
    public Boolean updateMenu(SysMenu menu) {
        int update = 0;
        try {
            update = menuMapper.updateById(menu);
        } catch (Exception e) {
            log.warn("updateMenu Exception =>>>>>>>>>>>>>>>>>>>>>>>>>>");
            e.printStackTrace();
            return false;
        }
        return update != 0 ;
    }

    /**
     * 删除菜单
     *
     * @param menuId
     * @return
     */
    @Override
    public Boolean deleteMenu(Long menuId) {

        // 先删除角色菜单表中的数据
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_id", menuId);

        // 删除菜单数据
        try {
            roleMenuMapper.delete(queryWrapper);
            return menuMapper.deleteById(menuId) != 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
